package cas.app;

import cas.client.User;
import cas.server.DB;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

@WebServlet(name = "MainPageServlet", urlPatterns = "/main-page")
public class MainPageServlet extends HttpServlet {

    // 主页，显示已登录的全部用户
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        request.setAttribute("account", user.getAccount());
        ArrayList<User> users = new ArrayList<>();
        try {
            DB.query(resultSet->{
                while (resultSet.next()) {
                    User aUser = new User();
                    aUser.setAccount(resultSet.getString(1));
                    aUser.setLoginTimestamp(resultSet.getTimestamp(2));
                    users.add(aUser);
                }
            }, "SELECT account, issued_at FROM token WHERE NOW() < expiration");
        } catch (SQLException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        users.sort(Comparator.comparing(User::getLoginTimestamp));
        request.setAttribute("users", users.toArray(new User[0]));
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/MainPage.jsp");
        dispatcher.forward(request, response);
    }

}
